package com.dev.op.util;

import com.dev.op.VO.SubmissionVO;
import com.dev.op.entity.SubTask;
import com.dev.op.entity.Submission;
import com.dev.op.VO.TaskVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String TOKEN_PREFIX = "login:";
    private static final String JUDGE_QUEUE_KEY = "judge:queue";
    private static final String SUB_QUEUE_KEY = "judge:task:queue";
    private static final String SUBMISSION_META_DATA = "judge:meta:";

    @Autowired
    private RedissonClient redissonClient;


    // 生产者：推送任务
    public void pushTask(SubmissionVO submissionVO) {
        RBlockingQueue<SubmissionVO> queue = redissonClient.getBlockingQueue(JUDGE_QUEUE_KEY);
        queue.add(submissionVO);
    }

     //消费者：阻塞获取任务
    public SubmissionVO blockingPopJudgeTask(Duration timeout) {
        RBlockingQueue<SubmissionVO> queue = redissonClient.getBlockingQueue(JUDGE_QUEUE_KEY);
        try {
            return queue.poll(timeout.toMillis(), TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return null;
        }
    }

    //子任务
//    public void pushSubTask(SubTask subTask) {
//        //System.out.println("尝试进入阻塞队列");
//        RBlockingQueue<SubTask> queue = redissonClient.getBlockingQueue(SUB_QUEUE_KEY);
//        queue.add(subTask);
//        //System.out.println("成功进入阻塞队列");
//    }

    public void pushSubTask(SubTask subTask) {
            redisTemplate.opsForList().rightPush("judge:task:queue", subTask);
    }


    //存入taskVO元信息
    public void pushSubmissionMetaData(TaskVO taskVO,int expireSeconds){
        redisTemplate.opsForValue().set( SUBMISSION_META_DATA + taskVO.getSubmissionId(), taskVO, Duration.ofSeconds(expireSeconds));
    }

    public TaskVO getSubmissionMetaData(String submissionId){
        Object obj = redisTemplate.opsForValue().get(SUBMISSION_META_DATA + submissionId );
        if (obj instanceof TaskVO taskVO) {
            return taskVO;
        }
        return null;
    }

    public SubTask popSubTask(Duration timeout) {
        RBlockingQueue<SubTask> queue = redissonClient.getBlockingQueue(SUB_QUEUE_KEY);
        //System.out.println("size大小："+queue.size());
//        try {
//            return queue.poll(timeout.toMillis(), TimeUnit.MILLISECONDS);
//        } catch (InterruptedException e) {
//            Thread.currentThread().interrupt();
//            return null;
//        }
        return queue.poll();

    }

    // 获取队列长度
    public long getJudgeQueueLength() {
        RBlockingQueue<Submission> queue = redissonClient.getBlockingQueue(JUDGE_QUEUE_KEY);
        return queue.size();
    }

    // 清空队列
    public void clearJudgeQueue() {
        RBlockingQueue<Submission> queue = redissonClient.getBlockingQueue(JUDGE_QUEUE_KEY);
        queue.clear();
    }



    /**
     *
     * 消息队列相关
     *
     */
//    //添加任务（左推，生产者）
//    //生产者具体方法
//    public void pushTask(Submission submission) {
//        redisTemplate.opsForList().leftPush(JUDGE_QUEUE_KEY, submission);
//    }
//
//    //获取任务（右取，消费者）
//    public Submission popTask() {
//        Object obj = redisTemplate.opsForList().rightPop(JUDGE_QUEUE_KEY);
//        if (obj instanceof Submission submission) {
//            return submission;
//        }
//        return null;
//    }
//
//    //获取队列长度（可用于状态监控）
//    public long getJudgeQueueLength() {
//        return redisTemplate.opsForList().size(JUDGE_QUEUE_KEY);
//    }
//
//    //阻塞式获取任务（带超时时间）
//    public Submission blockingPopJudgeTask(Duration timeout) {
//        Object obj = redisTemplate.opsForList().rightPop(JUDGE_QUEUE_KEY, timeout);
//        if (obj instanceof Submission submission) {
//            return submission;
//        }
//        return null;
//    }
//
//    //清空判题队列
//    public void clearJudgeQueue() {
//        redisTemplate.delete(JUDGE_QUEUE_KEY);
//    }

    /**
     *    Token相关
     *    Token相关
     */
    // 保存 token 有效期（单位秒）
    public void saveToken(String token, long expireSeconds) {
        redisTemplate.opsForValue().set( TOKEN_PREFIX+token, "", Duration.ofSeconds(expireSeconds));
    }
    // 检查 token 是否有效
    public boolean isTokenValid(String token) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(TOKEN_PREFIX + token));
    }
    // 删除 token（注销）
    public void deleteToken(String token) {
        redisTemplate.delete(TOKEN_PREFIX + token);

    }
    // 续期（可选）
    public void refreshToken(String token, long expireSeconds) {
        redisTemplate.expire(TOKEN_PREFIX + token, Duration.ofSeconds(expireSeconds));
    }
}
